# MCP Server工具 - MCP Server 包含多类工具
import os, sys
from pathlib import Path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../')))
from mcp.server.fastmcp import FastMCP
import json
import logging

from insight_agent.utils.http_post import get_insight_request, inform_insight_thinking, update_insight_result

mcp = FastMCP("Visualization")

# 构建文件读写路径
file_folder_path = Path(__file__).resolve().parent.parent.parent / "files"

@mcp.tool()
def visualize_sankey_chart(data: str) -> str:
    """
    用js的echart代码生成桑基图。输入为json字符串，格式为[{"source":..., "target":..., "value":...}, ...]
    
    输入格式说明:
    ============
    
    参数:
    - data: 桑基图数据，JSON字符串格式
    
    数据格式:
    =========
    
    桑基图数据格式 (data):
    [
        {"source": "A", "target": "B", "value": 100},
        {"source": "A", "target": "C", "value": 80},
        {"source": "B", "target": "D", "value": 60},
        {"source": "C", "target": "D", "value": 40}
    ]
    
    字段说明:
    =========
    - source: 源节点名称，字符串类型
    - target: 目标节点名称，字符串类型  
    - value: 流量值，必须是数字类型
    - 请根据用户原始query决定，source和target是什么，例如在query"请用桑基图分析20250701日 用户性别和全球通用户的关系"中，source是性别，target是全球通用户
    
    注意事项:
    =========
    1. 输入必须是有效的JSON字符串
    2. value字段必须是数字类型
    3. source和target字段必须是字符串类型
    
    示例:
    =====
    >>> sankey_data = [
    ...     {"source": "用户注册", "target": "完成验证", "value": 1000},
    ...     {"source": "完成验证", "target": "首次登录", "value": 800},
    ...     {"source": "首次登录", "target": "完成设置", "value": 600},
    ...     {"source": "完成设置", "target": "活跃用户", "value": 400}
    ... ]
    >>> import json
    >>> data_json = json.dumps(sankey_data)
    >>> result = visualize_sankey_chart(data_json)
    """
    inform_insight_thinking("agent_time_series", f'tools - visualize_sankey_chart')
    try:
        # 解析输入数据
        sankey_data = json.loads(data)
        logging.info(f"桑基图数据: {sankey_data}")
        
        # 验证数据格式
        if not isinstance(sankey_data, list):
            return "输入数据格式错误: 数据必须是数组格式"
        
        # 提取所有节点名称
        nodes = set()
        for item in sankey_data:
            if not isinstance(item, dict) or 'source' not in item or 'target' not in item or 'value' not in item:
                return "输入数据格式错误: 每个数据项必须包含source、target、value字段"
            
            if not isinstance(item['value'], (int, float)) or item['value'] <= 0:
                return "输入数据格式错误: value字段必须是正数"
            
            nodes.add(item['source'])
            nodes.add(item['target'])
        
        # 构建节点列表
        node_list = [{"name": node} for node in nodes]
        
        # 构建边列表
        links = []
        for item in sankey_data:
            links.append({
                "source": item['source'],
                "target": item['target'],
                "value": item['value']
            })
        
        # 生成ECharts配置
        echarts_config = {
            "title": {
                "text": "",
                "textStyle": {
                    "fontSize": 9,
                    "fontWeight": "bold"
                }
            },
            "tooltip": {
                "trigger": "item",
                "triggerOn": "mousemove"
            },
            "series": [
                {
                    "type": "sankey",
                    "layout": "none",
                    "data": node_list,
                    "links": links,
                    "itemStyle": {
                        "borderWidth": 1,
                        "borderColor": "#aaa"
                    },
                    "lineStyle": {
                        "color": "source",
                        "curvature": 0.5
                    },
                    "emphasis": {
                        "focus": "adjacency"
                    }
                }
            ]
        }
        
        echarts_config = json.dumps(echarts_config, ensure_ascii=False)

        import os
        # output_file = "sankey_chart.html"
        output_file_2 = "chart_option.json"
        # with open(file_folder_path / output_file, "w", encoding="utf-8") as f:
        #     f.write(html_content)

        with open(file_folder_path / output_file_2, "w", encoding="utf-8") as f:
            f.write(echarts_config)

        with open('chart_option.json', "w", encoding="utf-8") as f:
            f.write(echarts_config)
        
        return echarts_config
        
    except json.JSONDecodeError as e:
        return f"JSON解析错误: {e}"
    except Exception as e:
        return f"生成桑基图时发生错误: {e}"

@mcp.tool()
def visualize_line_chart(data, predict_data, query_key_parameter: str) -> str:
    """
    用js的echart代码生成折线图。输入分为两部分:
    1.已有数据，格式为[{"time":..., "value":...}, ...]
    2.预测数据，格式为[{"time":..., "value":...}, ...]
     要把两部分数据画在一张图中,但是用不同颜色表示,并且用不同的图标表示
     图表的标题为"时间序列数据与预测"
     图表的x轴为时间，y轴为指标值

    输入格式说明:
    ============

    参数:
    - data: 历史数据
    - predict_data: 预测数据
    - query_key_parameter (str): 前序工具query_processing生成的query关键参数

    数据格式:
    =========

    历史数据格式 (data):
    [
        {"time": "20240601", "value": 100},
        {"time": "20240602", "value": 120},
        {"time": "20240603", "value": 110}
    ]

    预测数据格式 (predict_data):
    [
        {"time": "20240604", "value": 130},
        {"time": "20240605", "value": 140}
    ]

    字段说明:
    =========
    - time: 时间标识，格式为YYYYMMDD（8位数字），如20240601表示2024年6月1日
    - value: 对应的数值，必须是数字类型

    注意事项:
    =========
    1. 预测数据的时间应该紧接着历史数据的最后一个时间点
    2. 时间格式必须为YYYYMMDD（8位数字）
    3. 数值字段必须是数字类型
    4. 输入必须是有效的JSON字符串
    5. 请确保传入的数据的是[{"time":..., "value":...}, ...]的格式，如果不是使用time和value，请修改符合要求再传入

    示例:
    =====
    >>> historical_data = [
    ...     {"time": "20240101", "value": 100},
    ...     {"time": "20240102", "value": 120},
    ...     {"time": "20240103", "value": 110}
    ... ]
    >>> prediction_data = [
    ...     {"time": "20240104", "value": 130},
    ...     {"time": "20240105", "value": 140}
    ... ]
    >>> import json
    >>> data_json = json.dumps(historical_data)
    >>> predict_json = json.dumps(prediction_data)
    >>> result = visualize_line_chart(data_json, predict_json)
    """
    # 用js的echart代码生成折线图
    # 假设data和predict_data均为JSON字符串，格式为[{"time":..., "value":...}, ...]

    inform_insight_thinking("agent_time_series", f'tools - visualize_line_chart')
    try:
        data_json = json.dumps(data)
        predict_json = json.dumps(predict_data)
        query_key_parameter = json.loads(query_key_parameter)

        caliber = "用户群体：" + query_key_parameter["user_scope"]
        caliber += " 统计指标：" + query_key_parameter["index"]
        caliber += " 开始时间：" + query_key_parameter["start_time"]
        caliber += " 结束时间：" + query_key_parameter["end_time"]

        data_points = json.loads(data_json)
        predict_points = json.loads(predict_json)
    except Exception as e:
        print("error")
        return f"输入数据格式错误: {e}"

    # 构造x轴和y轴数据
    x_data = [point["time"] for point in data_points] + [point["time"] for point in predict_points if point["time"] not in [p["time"] for p in data_points]]
    
    # 构造已有数据系列
    historical_data = [point["value"] for point in data_points]
    
    # 构造预测数据系列，从历史数据的最后一个点开始，前面用None填充
    predict_data = [None] * (len(data_points) - 1) + [historical_data[-1]]
    if data_points and predict_points:
        # 从历史数据的最后一个点开始
        for point in predict_points:
            predict_data.append(point["value"])
    
    # 生成ECharts配置
    echarts_config = {
        "title": {
            "text": f"统计口径 - {caliber}",
            "left": "center",
            "textStyle": {
                "fontSize": 18,
                "fontWeight": "bold"
            }
        },
        "tooltip": {
            "trigger": "axis",
            "axisPointer": {
                "type": "cross"
            }
        },
        "legend": {
            "data": ["已有数据", "预测数据"],
            "top": 30
        },
        "grid": {
            "left": "3%",
            "right": "4%",
            "bottom": "15%",
            "containLabel": True
        },
        "dataZoom": [
            {
                "type": "slider",
                "show": True,
                "xAxisIndex": [0],
                "start": 0,
                "end": 100,
                "bottom": "5%",
                "height": "5%",
                "borderColor": "transparent",
                "backgroundColor": "#f7f7f7",
                "fillerColor": "rgba(167,183,204,0.4)",
                "handleStyle": {
                    "color": "#5470C6",
                    "borderColor": "#5470C6"
                },
                "textStyle": {
                    "color": "#333"
                }
            },
            {
                "type": "inside",
                "xAxisIndex": [0],
                "start": 0,
                "end": 100
            }
        ],
        "xAxis": {
            "type": "category",
            "data": x_data,
            "name": "时序"
        },
        "dataZoom": [
            {
                "type": "slider",
                "show": True,
                "xAxisIndex": [0],
                "start": 0,
                "end": 100,
                "bottom": "5%",
                "height": "5%",
                "borderColor": "transparent",
                "backgroundColor": "#f7f7f7",
                "fillerColor": "rgba(167,183,204,0.4)",
                "handleStyle": {
                    "color": "#5470C6",
                    "borderColor": "#5470C6"
                },
                "textStyle": {
                    "color": "#333"
                }
            },
            {
                "type": "inside",
                "xAxisIndex": [0],
                "start": 0,
                "end": 100
            }
        ],
        "yAxis": {
            "type": "value",
            "name": "数值"
        },
        "series": [
            {
                "name": "预测数据",
                "type": "line",
                "data": predict_data,
                "itemStyle": {
                    "color": "#EE6666"
                },
                "lineStyle": {
                    "color": "#EE6666",
                    "type": "dashed",
                    "width": 3
                },
                "symbol": "diamond",
                "symbolSize": 8
            },
            {
                "name": "已有数据",
                "type": "line",
                "data": historical_data,
                "itemStyle": {
                    "color": "#5470C6"
                },
                "lineStyle": {
                    "color": "#5470C6",
                    "width": 3
                },
                "symbol": "circle",
                "symbolSize": 6
            }
        ]
    }

    echarts_config_for_frontend = {
        "title": {
            "text": f"统计口径 - {caliber}",
            "left": "center",
            "textStyle": {
                "fontSize": 12,
                "fontWeight": "bold"
            }
        },
        "tooltip": {
            "trigger": "axis",
            "axisPointer": {
                "type": "cross"
            }
        },
        "legend": {
            "data": ["已有数据", "预测数据"],
            "top": 30
        },
        "grid": {
            "left": "3%",
            "right": "6%",
            "bottom": "12%",
            "containLabel": True
        },
        "dataZoom": [
            {
                "type": "slider",
                "show": True,
                "xAxisIndex": [0],
                "start": 0,
                "end": 100,
                "bottom": "5%",
                "height": "5%",
                "borderColor": "transparent",
                "backgroundColor": "#f7f7f7",
                "fillerColor": "rgba(167,183,204,0.4)",
                "handleStyle": {
                    "color": "#5470C6",
                    "borderColor": "#5470C6"
                },
                "textStyle": {
                    "color": "#333"
                }
            },
            {
                "type": "inside",
                "xAxisIndex": [0],
                "start": 0,
                "end": 100
            }
        ],
        "xAxis": {
            "type": "category",
            "data": x_data,
            "name": "时序"
        },
        "dataZoom": [
            {
                "type": "slider",
                "show": True,
                "xAxisIndex": [0],
                "start": 0,
                "end": 100,
                "bottom": "5%",
                "height": "5%",
                "borderColor": "transparent",
                "backgroundColor": "#f7f7f7",
                "fillerColor": "rgba(167,183,204,0.4)",
                "handleStyle": {
                    "color": "#5470C6",
                    "borderColor": "#5470C6"
                },
                "textStyle": {
                    "color": "#333"
                }
            },
            {
                "type": "inside",
                "xAxisIndex": [0],
                "start": 0,
                "end": 100
            }
        ],
        "yAxis": {
            "type": "value",
            "name": "数值"
        },
        "series": [
            {
                "name": "预测数据",
                "type": "line",
                "data": predict_data,
                "itemStyle": {
                    "color": "#EE6666"
                },
                "lineStyle": {
                    "color": "#EE6666",
                    "type": "dashed",
                    "width": 3
                },
                "symbol": "diamond",
                "symbolSize": 8
            },
            {
                "name": "已有数据",
                "type": "line",
                "data": historical_data,
                "itemStyle": {
                    "color": "#5470C6"
                },
                "lineStyle": {
                    "color": "#5470C6",
                    "width": 3
                },
                "symbol": "circle",
                "symbolSize": 6
            }
        ]
    }

    echarts_config = json.dumps(echarts_config, ensure_ascii=False)
    echarts_config_for_frontend = json.dumps(echarts_config_for_frontend, ensure_ascii=False)

    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>时序模式可视化图表</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
    <style>
        body {{
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }}
        #chart {{
            width: 100%;
            height: 500px;
        }}
        .loading {{
            text-align: center;
            padding: 50px;
            color: #666;
        }}
    </style>
    </head>
    <body>
    <div class="container">
        <h1>时间序列数据可视化</h1>
        <div id="chart">
            <div class="loading">正在加载图表...</div>
        </div>
    </div>

    <script>
        // 等待页面加载完成
        document.addEventListener('DOMContentLoaded', function() {{
            // 检查ECharts是否加载成功
            if (typeof echarts === 'undefined') {{
                document.getElementById('chart').innerHTML = '<div class="loading">ECharts库加载失败，请检查网络连接</div>';
                return;
            }}

            try {{
                // 初始化图表
                var chartDom = document.getElementById('chart');
                var myChart = echarts.init(chartDom);

                var option = {echarts_config};

                myChart.setOption(option);

                // 响应式调整
                window.addEventListener('resize', function() {{
                    myChart.resize();
                }});

                console.log('图表加载成功');
            }} catch (error) {{
                console.error('图表初始化失败:', error);
                document.getElementById('chart').innerHTML = '<div class="loading">图表初始化失败: ' + error.message + '</div>';
            }}
        }});
    </script>
    </body>
    </html>
            """

    # 保存HTML到文件
    import os
    output_file = "time_series_chart.html"
    output_file_2 = "chart_option.json"
    with open(file_folder_path / output_file, "w", encoding="utf-8") as f:
        f.write(html_content)

    with open(file_folder_path / output_file_2, "w", encoding="utf-8") as f:
        f.write(echarts_config_for_frontend)

    print(f"HTML文件已保存到: {os.path.abspath(output_file)}")
    print("请在浏览器中打开该文件查看图表")

    return echarts_config_for_frontend

if __name__ == "__main__":
    mcp.run(transport='stdio')  # Run server via stdio
    # 测试一下函数能否生成网页可视化
    # a = [
    #     {"time": "20240601", "value": 5},
    #     {"time": "20240602", "value": 15},
    #     {"time": "20240603", "value": 25},
    #     {"time": "20240604", "value": 35},
    #     {"time": "20240605", "value": 45},
    #     {"time": "20240606", "value": 55},
    #     {"time": "20240607", "value": 65},
    #     {"time": "20240608", "value": 75},
    #     {"time": "20240609", "value": 85},
    #     {"time": "20240610", "value": 95},
    #     {"time": "20240611", "value": 105},
    #     {"time": "20240612", "value": 115},
    #     {"time": "20240613", "value": 125},
    #     {"time": "20240614", "value": 135},
    #     {"time": "20240615", "value": 145},
    #     {"time": "20240616", "value": 155},
    #     {"time": "20240617", "value": 165},
    #     {"time": "20240618", "value": 175},
    #     {"time": "20240619", "value": 185},
    #     {"time": "20240620", "value": 195}
    # ]
    
    # b = [
    #     {"time": "20240621", "value": 122.16},
    #     {"time": "20240622", "value": -109.47},
    #     {"time": "20240623", "value": -281.37},
    #     {"time": "20240624", "value": -131.86},
    #     {"time": "20240625", "value": 133.48},
    #     {"time": "20240626", "value": 227.72},
    #     {"time": "20240627", "value": 440.63},
    #     {"time": "20240628", "value": 1098.63},
    #     {"time": "20240629", "value": 1710.07},
    #     {"time": "20240630", "value": 1475.27},
    #     {"time": "20240701", "value": 567.76},
    #     {"time": "20240702", "value": 99.63},
    #     {"time": "20240703", "value": 396.36},
    #     {"time": "20240704", "value": 536.75},
    #     {"time": "20240705", "value": 258.63},
    #     {"time": "20240706", "value": 334.54},
    #     {"time": "20240707", "value": 603.36},
    #     {"time": "20240708", "value": 313.88},
    #     {"time": "20240709", "value": 57.55},
    #     {"time": "20240710", "value": 451.84},
    #     {"time": "20240711", "value": 632.37},
    #     {"time": "20240712", "value": 301.81},
    #     {"time": "20240713", "value": 395.82},
    #     {"time": "20240714", "value": 717.21},
    #     {"time": "20240715", "value": 372.51},
    #     {"time": "20240716", "value": 68.05},
    #     {"time": "20240717", "value": 531.94},
    #     {"time": "20240718", "value": 741.7},
    #     {"time": "20240719", "value": 352.74},
    #     {"time": "20240720", "value": 461.03}
    # ]
    
    # # 测试 visualize_line_chart 函数能否生成网页可视化代码
    # visualize_line_chart(a,b)


